package com.dream.myqiyi.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.dream.myqiyi.BaseApp;
import com.dream.myqiyi.Global;
import com.dream.myqiyi.dao.NoteModel;
import com.dream.myqiyi.dao.NotebookModel;
import com.dream.myqiyi.service.ApplicationContext;
import com.dream.myqiyi.service.NoteResourceService;
import com.dream.myqiyi.service.NoteService;
import com.dream.myqiyi.service.NotebookService;
import com.dream.myqiyi.service.TagService;

public class NoteSync {
	
	public void getNotes() {
		String strUrl = Global.SERVER_URL + Global.DEFAULT_USERNAME + "/notes";
//		HttpGet httpRequest = new HttpGet(strUrl);
		HttpPost httpRequest = new HttpPost(strUrl);
		
		HttpClient httpClient = HttpUtils.getNewHttpClient(BaseApp.context);
		
		try {
			HttpResponse httpResponse = httpClient.execute(httpRequest);
			String strResult;
			if(httpResponse.getStatusLine().getStatusCode() == 200) {
				strResult = EntityUtils.toString(httpResponse.getEntity());
				//msgTextView.setText(strResult);
			} else {
				strResult = EntityUtils.toString(httpResponse.getEntity());
				//msgTextView.setText(strResult);
			}
			System.out.println(strResult);
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void getNote(String guid) {
		String strUrl = Global.SERVER_URL + "notes/";
		strUrl += guid;
//		HttpGet httpRequest = new HttpGet(strUrl);
		HttpPost httpRequest = new HttpPost(strUrl);
		
		HttpClient httpClient = HttpUtils.getNewHttpClient(BaseApp.context);
		
		try {
			HttpResponse httpResponse = httpClient.execute(httpRequest);
			String strResult;
			if(httpResponse.getStatusLine().getStatusCode() == 200) {
				strResult = EntityUtils.toString(httpResponse.getEntity());
				//msgTextView.setText(strResult);
			} else {
				strResult = EntityUtils.toString(httpResponse.getEntity());
				//msgTextView.setText(strResult);
			}
			System.out.println(strResult);
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public boolean updateNote(String guid) {
		String strUrl = Global.SERVER_URL + "notes";
//		HttpGet httpRequest = new HttpGet(strUrl);
		HttpPost httpRequest = new HttpPost(strUrl);
		
		NoteService noteSrv = (NoteService)ApplicationContext.getSingleton().getBean("NoteService");
		NoteModel note = noteSrv.getNote(guid);
		if (note == null) {
			return false;
		}
		JSONObject noteParam = noteSrv.toJsonData(note);
		if (noteParam == null) {
			return false;
		}
		
		try {
			StringEntity se = new StringEntity(noteParam.toString());
			httpRequest.setEntity(se);
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return false;
		}
		
		
		HttpClient httpClient = HttpUtils.getNewHttpClient(BaseApp.context);
		
		try {
			HttpResponse httpResponse = httpClient.execute(httpRequest);
			String strResult;
			if(httpResponse.getStatusLine().getStatusCode() == 200) {
				strResult = EntityUtils.toString(httpResponse.getEntity());
				//msgTextView.setText(strResult);
			} else {
				strResult = EntityUtils.toString(httpResponse.getEntity());
				//msgTextView.setText(strResult);
			}
			System.out.println(strResult);
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return true;
	}
	
	public void delNote(String guid) {
		
	}
	
	public void getNotebooks() {
		String strUrl = Global.SERVER_URL + Global.DEFAULT_USERNAME + "/notebooks";
//		HttpGet httpRequest = new HttpGet(strUrl);
		HttpPost httpRequest = new HttpPost(strUrl);
		
		HttpClient httpClient = HttpUtils.getNewHttpClient(BaseApp.context);
		
		try {
			HttpResponse httpResponse = httpClient.execute(httpRequest);
			String strResult;
			if(httpResponse.getStatusLine().getStatusCode() == 200) {
				strResult = EntityUtils.toString(httpResponse.getEntity());
				//msgTextView.setText(strResult);
			} else {
				strResult = EntityUtils.toString(httpResponse.getEntity());
				//msgTextView.setText(strResult);
			}
			
			try {
				NotebookService nbSrc = (NotebookService)ApplicationContext.getSingleton().getBean("NotebookService");
				JSONArray jsonArr = new JSONArray(strResult);
				for (int i=0; i<jsonArr.length(); ++i) {
					JSONObject nbParam = jsonArr.getJSONObject(i);
					NotebookModel nb = nbSrc.fromJsonData(nbParam);
					if (nb != null) {
						nbSrc.updateNotebook(nb);
					}
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	public boolean updateNotebook(String guid) {
		NotebookService nbSrv = (NotebookService)ApplicationContext.getSingleton().getBean("NotebookService");
		if (nbSrv == null) {
			return false;
		}
		NotebookModel nb = nbSrv.findNotebook(guid);
		if (nb == null) {
			return false;
		}
		JSONObject nbParam = nbSrv.toJsonData(nb);
		if (nbParam == null) {
			return false;
		}
		
		String strUrl = Global.SERVER_URL + "notebooks";
//		HttpGet httpRequest = new HttpGet(strUrl);
		HttpPost httpRequest = new HttpPost(strUrl);
		StringEntity se;
		try {
			se = new StringEntity(nbParam.toString());
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			return false;
		}
		httpRequest.setEntity(se);
		
		HttpClient httpClient = HttpUtils.getNewHttpClient(BaseApp.context);
		
		try {
			HttpResponse httpResponse = httpClient.execute(httpRequest);
			String strResult;
			if(httpResponse.getStatusLine().getStatusCode() == 200) {
				strResult = EntityUtils.toString(httpResponse.getEntity());
				//msgTextView.setText(strResult);
			} else {
				strResult = EntityUtils.toString(httpResponse.getEntity());
				//msgTextView.setText(strResult);
			}
			
			try {
				JSONObject result = new JSONObject(strResult);
				String ret = result.getString("success");
				return Boolean.getBoolean(ret);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public boolean delNotebook(String guid) {
		String strUrl = Global.SERVER_URL + "notebooks/" + guid;
//		HttpGet httpRequest = new HttpGet(strUrl);
		HttpPost httpRequest = new HttpPost(strUrl);
		
		HttpClient httpClient = HttpUtils.getNewHttpClient(BaseApp.context);
		try {
			HttpResponse httpResponse = httpClient.execute(httpRequest);
			String strResult;
			if(httpResponse.getStatusLine().getStatusCode() == 200) {
				strResult = EntityUtils.toString(httpResponse.getEntity());
				//msgTextView.setText(strResult);
			} else {
				strResult = EntityUtils.toString(httpResponse.getEntity());
				//msgTextView.setText(strResult);
			}
			
			try {
				JSONObject result = new JSONObject(strResult);
				String ret = result.getString("success");
				return Boolean.getBoolean(ret);
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public void getTags() {
		String strUrl = Global.SERVER_URL + Global.DEFAULT_USERNAME + "/tags";
//		HttpGet httpRequest = new HttpGet(strUrl);
		HttpPost httpRequest = new HttpPost(strUrl);
		
		HttpClient httpClient = HttpUtils.getNewHttpClient(BaseApp.context);
		
		try {
			HttpResponse httpResponse = httpClient.execute(httpRequest);
			String strResult;
			if(httpResponse.getStatusLine().getStatusCode() == 200) {
				strResult = EntityUtils.toString(httpResponse.getEntity());
				//msgTextView.setText(strResult);
			} else {
				strResult = EntityUtils.toString(httpResponse.getEntity());
				//msgTextView.setText(strResult);
			}
			
			try {
				TagService tagSrc = (TagService)ApplicationContext.getSingleton().getBean("TagService");
				JSONArray jsonArr = new JSONArray(strResult);
				for (int i=0; i<jsonArr.length(); ++i) {
					tagSrc.addTag(jsonArr.getString(i));
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void getRes(String guid) {
		String strUrl = Global.SERVER_URL + "resources/" + guid;
//		HttpGet httpRequest = new HttpGet(strUrl);
		HttpPost httpRequest = new HttpPost(strUrl);
		
		HttpClient httpClient = HttpUtils.getNewHttpClient(BaseApp.context);
		
		try {
			HttpResponse httpResponse = httpClient.execute(httpRequest);
			StringBuilder strResult;
			if(httpResponse.getStatusLine().getStatusCode() == 200) {
				strResult = inputStreamToString(httpResponse.getEntity().getContent());
				//msgTextView.setText(strResult);
			} else {
				strResult = inputStreamToString(httpResponse.getEntity().getContent());
				//msgTextView.setText(strResult);
			}
			
			NoteResourceService nrSrv = (NoteResourceService)ApplicationContext.getSingleton().getBean("NoteResourceService");
			System.out.println(strResult);
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public boolean updateRes(String guid) {
		return true;
	}
	
	// Fast Implementation
	private StringBuilder inputStreamToString(InputStream is) {
	    String line = "";
	    StringBuilder total = new StringBuilder();
	    
	    // Wrap a BufferedReader around the InputStream
	    BufferedReader rd = new BufferedReader(new InputStreamReader(is));

	    // Read response until the end
	    try {
			while ((line = rd.readLine()) != null) { 
			    total.append(line); 
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	    // Return full string
	    return total;
	}
}
